using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Threading;

namespace Krile.Forms.Dialogs.Popup
{

    public partial class Splash : Form
    {
        public Splash()
        {
            InitializeComponent();
            this.Opacity = 0;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
            e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
            Rectangle rect = this.ClientRectangle;
            using (var b = new LinearGradientBrush(this.ClientRectangle, Color.White, Color.MintCream, 90))
            {
                b.GammaCorrection = true;
                e.Graphics.FillRectangle(b, rect);
            }
            Rectangle outer = this.ClientRectangle;
            outer.Width--;
            outer.Height--;
            e.Graphics.DrawRectangle(Pens.PowderBlue, outer);
            base.OnPaint(e);
        }


        private void Splash_Load(object sender, EventArgs e)
        {
            versionLabel.Text = "Version " + Define.VersionString;
        }

        /// <summary>
        /// Thread safe.
        /// </summary>
        internal void SetLoadingLabel(string label)
        {
            this.SafeOperate<string>((s) =>
            {
                this.Visible = true;
                timeoutable = false;
                loadingLabel.Text = label;
                loadingLabel.Refresh();
            }, label);
        }

        bool timeoutable = false;
        internal void SetTimeout(int intv)
        {
            Action act = () =>
                {
                    timeoutable = true;
                    Thread.Sleep(intv);
                    if (timeoutable)
                    {
                        this.SafeOperate(() => this.Visible = false);
                    }
                };
            act.BeginInvoke((iar) => ((Action)iar.AsyncState).EndInvoke(iar), act);
        }

        private void Splash_Shown(object sender, EventArgs e)
        {
            for (int i = 0; i <= 25; i++)
            {
                this.Opacity = i / 25.0;
                System.Threading.Thread.Sleep(10);
            }
        }

        private void Splash_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.InvokeRequired)
            {
                this.SafeOperate(
                    new Action(() =>
                        {
                            for (int i = 25; i >= 0; i--)
                            {
                                this.Opacity = i / 25.0;
                                System.Threading.Thread.Sleep(10);
                            }

                        }));
            }
        }
    }
}